<!DOCTYPE html>
<html>
  <head>
    <!--Import Google Icon Font-->
    <link type="text/css" rel="stylesheet" href="css/material-icons.css"/>
    <!--Import materialize.css-->
    <link type="text/css" rel="stylesheet" href="css/materialize.min.css"  media="screen,projection"/>
    <title>Instances Status In Cell</title>

    <!--Let browser know website is optimized for mobile-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <style>
    nav.clean{
        background: none;
        box-shadow: none;
    }

    .breadcrumb:before {
        color: rgba(0,0,0,0.7);
    }

    .breadcrumb, .breadcrumb:last-child {
       color: rgba(0,0,0,1);
    }
    </style>

  </head>
  <body>

  <div class="container">
    <div class="section">
      <nav class="clean">
         <div class="nav-wrapper">
           <div class="col s12" id="breadcrumb-path">
             <a href="dashboard.html" class="breadcrumb" id="zone-caption"></a>
             <a href="pool_status.html" class="breadcrumb" id="pool-caption"></a>
            </div>
        </div>
      </nav>
      <div class="divider"></div>
    </div>

    <div class="section">
      <div class="row" id="status_list">
      </div>
    </div>
  </div>

  <!--JavaScript at end of body for optimized loading-->
  <script type="text/javascript" src="js/materialize.min.js"></script>
  <script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
  <script type="text/javascript" src="js/Chart.bundle.min.js"></script>
  <script type="text/javascript" src="js/nano.js"></script>
  <script>
    N.ValidateSession();
    var texts = N.GetTexts();
    $('#zone-caption').text(texts.get(N.TagZone));
    $('#pool-caption').text(texts.get(N.TagComputePool));

    M.AutoInit();
    var poolName;
    var cellName;
    function parseQueryString(){
      var url = window.location.search;
      var queryString = url.substring( url.indexOf('?') + 1 );
      if (0 === queryString.length){
        M.toast({html: 'no query string available', outDuration: 1500});
        return false;
      }
      var values = queryString.split("&");
      var params = new Map();
      values.forEach((value) => {
        var p = value.split('=');
        params.set(p[0], p[1]);
      });
      if (0 == params.length){
        M.toast({html: 'invalid query string', outDuration: 1500});
        return false;
      }
      if (!params.has('pool')){
        M.toast({html: 'Must specify pool name', outDuration: 1500});
        return false;
      }
      poolName = params.get('pool');
      if (params.has('cell')){
        cellName = params.get('cell');
      }
      return true;
    }
    var statusMap = new Map();

    function addStatus(instanceID, instanceName){
      var cardTitle = $('<span>').addClass('card-title').text(instanceName).prepend(
        $('<i>').addClass('material-icons blue-grey-text darken-2').text('cloud_queue')
      );
      var tbody = $('<tbody>').append(
        $('<tr>').append(
          $('<td>').text(texts.get(N.TagCore))
        ).append(
          $('<td>').attr('id', 'core-' + instanceID)
        ).append(
          $('<td>').text(texts.get(N.TagDisk))
        ).append(
          $('<td>').attr('id', 'disk-' + instanceID)
        )
      ).append(
        $('<tr>').append(
          $('<td>').text(texts.get(N.TagMemory))
        ).append(
          $('<td>').attr('id', 'memory-' + instanceID)
        ).append(
          $('<td>')
        ).append(
          $('<td>').attr('id', 'icon-' + instanceID)
        )
      )
      var table = $('<table>').addClass('striped').append(tbody);

      var cardContent = $('<div>').addClass('card-content').append(cardTitle).append(table);
      var cardActions = $('<div>').addClass('card-action').attr('id', 'action-' + instanceID);
      var status = $('<div>', {id: 'status-' + instanceID}).addClass('col m6 s12').append(
        $('<div>').addClass('card small').append(cardContent).append(cardActions)
      );
      $('#status_list').append(status);
      statusMap.set(instanceID, {'created': undefined, 'running': undefined});
    }

    function updateChart(data){
      var instanceID = data['id'];
      $('#core-' + instanceID).text(data['cores']);
      var mib = 1 << 20;
      var gib = 1 << 30;
      $('#memory-' + instanceID).text(data['memory'] / mib + ' MiB');
      var disks = new Array();
      data['disks'].forEach((size) => {
        disks.push(size / gib);
      });
      $('#disk-' + instanceID).text(disks.join(' / ') + ' GiB');
      var created = statusMap.get(instanceID).created;
      var running = statusMap.get(instanceID).running;
      if (created != data['created']){
        created = data['created'];
        statusMap.get(instanceID).created = created;
        $('#action-' + instanceID).empty();
        if (created){
          //not created => created
          $('#action-' + instanceID).append($('<a>', {'href': 'monitor_instance_status.html?cell='+ cellName + '&pool=' + poolName + '&instance=' + instanceID,  'data-position': 'bottom', 'data-tooltip': texts.get(N.TagMonitor)}).addClass('blue-grey-text tooltipped').append(
            $('<i>').addClass('material-icons').text('insert_chart')
          ));
        }else{
          //=>creating
          $('#action-' + instanceID).append(
            $('<div>').addClass('progress').append(
              $('<div>').addClass('determinate darken-2 tooltipped').attr('data-position', 'top').attr('id', 'progress-' + instanceID)
            )
          )
        }
      }
      if (!created){
        //update progress
        var progress = data['progress'] + '%';
        $('#progress-' + instanceID).attr('data-tooltip', 'creating progress ' + progress).width(progress);
      }

      if (running != data['running']){
        running = data['running'];
        statusMap.get(instanceID).running = running;
        if (running){
          //stop=>running
          if ($('#stop-icon-' + instanceID)){
            $('#stop-icon-' + instanceID).remove();
          }
          $('#icon-' + instanceID).append(
            $('<i>').text('play_arrow').addClass(
              'material-icons green-text darken-2 tooltipped'
            ).attr('data-position', 'top').attr('data-tooltip', texts.get(N.TagRunning)).attr('id', 'running-icon-' + instanceID)
          )
        }else{
          //running=>stop
          if ($('#running-icon-' + instanceID)){
            $('#running-icon-' + instanceID).remove();
          }
          $('#icon-' + instanceID).append(
            $('<i>').text('stop').addClass(
              'material-icons red-text darken-2 tooltipped'
            ).attr('data-position', 'top').attr('data-tooltip', texts.get(N.TagStopped)).attr('id', 'stop-icon-' + instanceID)
          )
        }
      }
      M.Tooltip.init($('.tooltipped'));
    }

    function updateDashboard(){
      var url;
      if (cellName){
        url = "/instance_status/" + poolName + "/" + cellName;
      }else{
        url = "/instance_status/" + poolName;
      }
      $.getJSON(url, function(result){
        if (0 != result['error_code']) {
            M.toast({html: 'update instance status fail:' + result['message']});
            return;
        }
        if (!result['data']){
          M.toast({html: 'no instance data available'});
          return;
        }
        var clearTarget = new Set();
        for(var instanceID of statusMap.keys()){
          clearTarget.add(instanceID);
        }
        result['data'].forEach((data) => {
          var instanceID = data['id'];
          if (!statusMap.has(instanceID)){
            var name = data['name'];
            addStatus(instanceID, name);
          }
          updateChart(data);
          if (clearTarget.has(instanceID)){
            clearTarget.delete(instanceID)
          }
        });
        clearTarget.forEach((instanceID) =>{
          $('#status-' + instanceID).remove();
          statusMap.delete(instanceID);
        });
      });
    }

    if (parseQueryString()){
      if (undefined != cellName){
        $('#breadcrumb-path').append(
          $('<a>').addClass('breadcrumb').text(poolName).attr('href','cell_status.html?pool=' + poolName)
        ).append(
          $('<a>').addClass('breadcrumb').text(cellName).attr('href','#')
        );
      }else{
        $('#breadcrumb-path').append(
          $('<a>').addClass('breadcrumb').text(poolName).attr('href','#')
        );
      }
      updateDashboard();
      setInterval(updateDashboard, 2000);
    }
  </script>
  </body>
</html>
